<?php

namespace app\api\controller;

use app\common\model\Relation;
use app\traits\Help;
use app\traits\Until;
use think\Controller;
use think\Db;
use think\Request;
use app\common\model\User;

use think\Validate;

class Auth extends Base
{
    use Help;

    //注册
    public function register()
    {
        $params   = $this->request->param();
        $validate = new Validate([
            'email' => 'require|email',
            'email_code' => 'require',
            'password' => 'require|alphaNum|length:8,25',
            'invite_code' => 'require',
        ], [
            'email.require' => '邮箱必须'
        ]);
        if (!$validate->check($params)) {
            return $this->fail($validate->getError(), 1010);
        }
        $email       = $params['email'];
        $email_code  = $params['email_code'];
        $invite_code = $params['invite_code'];
        //TODO::验证邮箱
        if (!$this->checkEmailCode($email, $email_code)) {
            return $this->fail('邮箱验证码错误', 1011);
        }
        //验证是否已经注册过
        $has = User::where('email', $email)->find();
        if ($has) return $this->fail('该邮箱已经注册过', 1016);
        //TODO::验证邀请码
        if ($invite_code !== 'MMPa') {
            $puser = User::where('invite_code', $invite_code)->find();
            if (!$puser) return $this->fail('邀请码错误', 1012);
        }
        //获取关联关系
        $relation              = Relation::where('user_id', $puser->id)->find();
        $new_user              = new User();
        $new_user->email       = $email;
        $new_user->password    = password_hash($params['password'], 1);
        $new_user->username    = $email;
        $new_user->invite_code = Until::strRandom();
        $new_user->time        = date('Y-m-d H:i:s', time());

        $new_relation       = new Relation();
        $new_relation->pid1 = $puser->id;
        $new_relation->pid2 = $relation->pid1;
        Db::startTrans();
        try {
            $new_user->save();
            $new_relation->user_id = $new_user->id;
            $new_relation->save();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->fail('注册失败', 1015);
        }
        return $this->renderJson();
    }


    //登陆
    public function login()
    {
        $params   = $this->request->param();
        $validate = new Validate([
            'email' => 'require|email',
            'password' => 'require|alphaNum|length:8,25',
        ], [
            'email.require' => '邮箱必须'
        ]);
        if (!$validate->check($params)) {
            return $this->fail($validate->getError(), 1010);
        }
        $email    = $params['email'];
        $password = $params['password'];
        $user     = User::where('email', $email)->find();
        if (!$user) return $this->fail('该账户未注册', 1013);
        if (!password_verify($password, $user->password)) {
            return $this->fail('密码错误', 1014);
        }
        if ($user->status != 'normal') return $this->fail('改账号已冻结', 1015);

        $token    = Until::createToken($user->id);
        $exp_time = time() + 86400;

        $user->token      = $token;
        $user->exp_time   = $exp_time;
        $user->login_time = date('Y-m-d H:i:s', time());
        $user->save();
        $data['token']    = $token;
        $data['exp_time'] = $exp_time;
        return $this->renderJson($data);
    }

    //退出登陆
    public function logout()
    {
        $user           = $this->user();
        $user->token    = '';
        $user->exp_time = 0;
        $user->save();
        return $this->renderJson();
    }


    //修改密码
    public function modifyPassword()
    {
        $params   = $this->request->param();
        $validate = new Validate([
            'old_password' => 'require|alphaNum|length:8,25',
            'new_password' => 'require|alphaNum|length:8,25',
        ], [
            'old_password.require' => '原密码必须'
        ]);
        if (!$validate->check($params)) {
            return $this->fail($validate->getError(), 1020);
        }
        $old_password = $params['old_password'];
        $new_password = $params['new_password'];
        if ($old_password == $new_password) {
            return $this->fail('新密码与原密码相同', 1022);
        }
        $user = $this->user();
        if (!password_verify($old_password, $user->password)) {
            return $this->fail('原密码错误', 1021);
        }
        $user->password = password_hash($new_password, 1);
        //修改成功退出登陆
        $user->token    = '';
        $user->exp_time = 0;
        if ($user->save()) {
            return $this->renderJson();
        }
        return $this->fail('修改失败', 10023);
    }


    //忘记密码--找回
    public function findPassword()
    {
        $params   = $this->request->param();
        $validate = new Validate([
            'email' => 'require|email',
            'email_code' => 'require|length:4,10',
            'new_password' => 'require|alphaNum|length:8,25',
        ], [
            'email.require' => '邮箱必须'
        ]);
        if (!$validate->check($params)) {
            return $this->fail($validate->getError(), 1030);
        }
        $email_code = $params['email_code'];
        $email      = $params['email'];
        if (!$this->checkEmailCode($email, $email_code)) {
            return $this->fail('邮箱验证码错误', 1032);
        }

        $user           = User::where('email', $email)->find();
        $new_password   = $params['new_password'];
        $user->password = password_hash($new_password, 1);

        if ($user->save()) {
            return $this->renderJson();
        }
        return $this->fail('修改失败', 1031);
    }


}
